import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class DormitoryAdjuster:
    def __init__(self):
        self.db = Database()
    
    def adjust_dormitory(self, student_id, new_dormitory_id):
        """
        调整学生宿舍
        
        参数:
            student_id (str): 学生学号
            new_dormitory_id (int): 新宿舍ID
        
        返回:
            bool: 调整成功返回True，否则返回False
        """
        try:
            # 验证输入
            if not student_id or not new_dormitory_id:
                print("错误：学生学号和新宿舍ID都必须提供")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查学生是否存在
            self.db.cursor.execute(
                "SELECT id, name, gender, dormitory_id FROM student WHERE student_id = ?",
                (student_id,)
            )
            student = self.db.cursor.fetchone()
            if not student:
                print(f"错误：学号为 {student_id} 的学生不存在")
                self.db.close()
                return False
            
            student_db_id, student_name, student_gender, current_dormitory_id = student
            
            # 检查学生是否已分配宿舍
            if not current_dormitory_id:
                print(f"错误：学生 {student_name} 尚未分配宿舍，无法调整")
                self.db.close()
                return False
            
            # 检查新宿舍是否与当前宿舍相同
            if int(current_dormitory_id) == int(new_dormitory_id):
                print(f"错误：新宿舍与当前宿舍相同，无需调整")
                self.db.close()
                return False
            
            # 获取当前宿舍信息
            self.db.cursor.execute(
                "SELECT building, room_number FROM dormitory WHERE id = ?",
                (current_dormitory_id,)
            )
            current_dorm = self.db.cursor.fetchone()
            if not current_dorm:
                print(f"错误：无法获取当前宿舍信息")
                self.db.close()
                return False
            
            current_building, current_room = current_dorm
            
            # 检查新宿舍是否存在
            self.db.cursor.execute(
                "SELECT id, building, room_number, capacity, current_count, status FROM dormitory WHERE id = ?",
                (new_dormitory_id,)
            )
            new_dormitory = self.db.cursor.fetchone()
            if not new_dormitory:
                print(f"错误：ID为 {new_dormitory_id} 的宿舍不存在")
                self.db.close()
                return False
            
            dorm_id, building, room_number, capacity, current_count, status = new_dormitory
            
            # 检查新宿舍状态
            if status != 'available':
                print(f"错误：宿舍 {building}-{room_number} 当前状态为 {status}，不可分配")
                self.db.close()
                return False
            
            # 检查新宿舍是否已满
            if current_count >= capacity:
                print(f"错误：宿舍 {building}-{room_number} 已满员 ({current_count}/{capacity})")
                self.db.close()
                return False
            
            # 检查新宿舍性别匹配
            if current_count > 0:
                # 获取宿舍内学生的性别
                self.db.cursor.execute(
                    """SELECT s.gender FROM student s 
                    WHERE s.dormitory_id = ? LIMIT 1""",
                    (dorm_id,)
                )
                dorm_gender = self.db.cursor.fetchone()
                if dorm_gender and dorm_gender[0] != student_gender:
                    print(f"错误：宿舍 {building}-{room_number} 已有不同性别的学生")
                    self.db.close()
                    return False
            
            # 更新原宿舍分配记录状态为inactive
            self.db.cursor.execute(
                "UPDATE allocation SET status = 'inactive' WHERE student_id = ? AND dormitory_id = ? AND status = 'active'",
                (student_db_id, current_dormitory_id)
            )
            
            # 更新学生的宿舍ID
            self.db.cursor.execute(
                "UPDATE student SET dormitory_id = ? WHERE id = ?",
                (dorm_id, student_db_id)
            )
            
            # 减少原宿舍当前人数
            self.db.cursor.execute(
                "UPDATE dormitory SET current_count = current_count - 1 WHERE id = ?",
                (current_dormitory_id,)
            )
            
            # 增加新宿舍当前人数
            self.db.cursor.execute(
                "UPDATE dormitory SET current_count = current_count + 1 WHERE id = ?",
                (dorm_id,)
            )
            
            # 添加新的分配记录
            allocation_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.db.cursor.execute(
                "INSERT INTO allocation (student_id, dormitory_id, allocation_date, status) VALUES (?, ?, ?, ?)",
                (student_db_id, dorm_id, allocation_date, 'active')
            )
            
            self.db.conn.commit()
            print(f"成功：学生 {student_name} 已从宿舍 {current_building}-{current_room} 调整到宿舍 {building}-{room_number}")
            return True
        except Exception as e:
            print(f"错误：调整宿舍时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    adjuster = DormitoryAdjuster()
    
    print("===== 宿舍调整 =====")
    student_id = input("请输入学生学号: ")
    new_dormitory_id = input("请输入新宿舍ID: ")
    
    try:
        new_dormitory_id = int(new_dormitory_id)
        adjuster.adjust_dormitory(student_id, new_dormitory_id)
    except ValueError:
        print("错误：宿舍ID必须是数字")